CREATE OR REPLACE FUNCTION number_of_sends(integer, integer, integer)
  RETURNS integer AS
'
declare
    in_erid alias for $1;
    in_days alias for $2;
    in_product_id alias for $3;

    sends integer;
    date_interval text;
begin

    date_interval = in_days||'' days'';

    SELECT INTO sends COUNT(qn.qnid) FROM queuenodes qn INNER JOIN queues q on qn.qid = q.id
    WHERE qn.id = in_erid AND q.product_id = in_product_id 
    AND qn.sent = true AND qn.skipped = false
    AND qn.send_date BETWEEN current_date - date_interval::INTERVAL  AND current_date;

    return sends;
end;
'
  LANGUAGE 'plpgsql' VOLATILE;
ALTER FUNCTION number_of_sends(integer, integer, integer) OWNER TO mavmail;